package com.fable.web.controller.user;

import com.alibaba.fastjson.JSON;
import com.fable.biz.operate.AdminRoleService;
import com.fable.biz.operate.AdminUserService;
import com.fable.biz.operate.CreateAdminRoleModel;
import com.fable.biz.operate.CreateAdminUserModel;
import com.fable.common.config.RequireLogin;
import com.fable.common.utils.JsonResult;
import com.fable.dal.condition.AdminUserQueryCondition;
import com.fable.dal.dto.AdminUserDTO;
import com.fable.dal.mapper.ext.AdminUserExtMapper;
import com.fable.dal.model.AdminRoleDO;
import com.fable.dal.model.AdminRoleQuery;
import com.fable.dal.model.AdminUserDO;
import com.fable.dal.model.AdminUserQuery;
import com.fable.web.common.admin.UserTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * Created by weishuai on 18/7/21.
 */
@Controller
@RequireLogin
@RequestMapping("/adminUser")
public class AdminUserController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    AdminUserService adminUserService;

    @Autowired
    AdminRoleService adminRoleService;

    @Autowired
    AdminUserExtMapper adminUserExtMapper;

    @RequestMapping("/adminUserList.htm")
    public String list(ModelMap model, AdminUserQueryCondition condition, HttpSession session) {
        Long loginId=UserTools.getLoginId(session);
        List<AdminUserDTO> list = adminUserService.findUser(condition);
        model.put("list", list);
        model.put("query", condition);
        return "user/adminUserList";
    }

    @RequestMapping("/adminUserPwdEdit.htm")
    public String adminUserPwdEdit(HttpServletRequest request, ModelMap model, Integer id) {
        if (id != null) {
            AdminUserDTO adminUserDTO = adminUserService.findDTOUserById(id);
            model.put("result", adminUserDTO);
        }
        return "user/adminUserPwdEdit";
    }

    @RequestMapping("/adminUserAdd.htm")
    public String add(HttpServletRequest request, ModelMap model, Integer id) {
        //id不为空则说明是点击修改过来的
        AdminUserQueryCondition condition=new AdminUserQueryCondition();
        List<AdminUserDTO> userDTOList=adminUserService.findUser(condition);
        model.put("userList",userDTOList);
        AdminRoleQuery roleQuery=new AdminRoleQuery();
        List<AdminRoleDO> roleList=adminRoleService.selectByQuery(roleQuery);
        model.put("roleList",roleList);

        if (id != null) {
            AdminUserDTO adminUserDTO = adminUserService.findDTOUserById(id);
            model.put("result", adminUserDTO);
        }
        return "user/adminUserAdd";
    }

    @RequestMapping("/delAdminUser.json")
    @ResponseBody
    public JsonResult delete(HttpServletRequest request, Integer id) {
        JsonResult result = new JsonResult();
//        AdminUserDO adminDO = (AdminUserDO) request.getSession().getAttribute(FableConstant.USER_SESSION_KEY);
//        if (adminDO == null) {
//            result.setErrMsg("请重新登录!");
//            return result;
//        }
        if (id != null) {
            AdminUserDO adminUserDO = adminUserService.findDOUserById(id);
            if (adminUserDO == null) {
                result.setErrMsg("对象不存在!");
                return result;
            } else {
                adminUserDO.setStatus(-1);
                adminUserService.update(adminUserDO);
            }
        }
        return result;
    }

    @RequestMapping("/startAdminUser.json")
    @ResponseBody
    public JsonResult start(HttpServletRequest request, Integer id) {
        JsonResult result = new JsonResult();
//        AdminUserDO adminDO = (AdminUserDO) request.getSession().getAttribute(FableConstant.USER_SESSION_KEY);
//        if (adminDO == null) {
//            result.setErrMsg("请重新登录!");
//            return result;
//        }
        if (id != null) {
            AdminUserDO adminUserDO = adminUserService.findDOUserById(id);
            if (adminUserDO == null) {
                result.setErrMsg("对象不存在!");
                return result;
            } else {
                adminUserDO.setStatus(1);
                adminUserService.update(adminUserDO);
            }
        }
        return result;
    }


    @RequestMapping("/stopAdminUser.json")
    @ResponseBody
    public JsonResult stop(HttpServletRequest request, Integer id) {
        JsonResult result = new JsonResult();
//        AdminUserDO adminDO = (AdminUserDO) request.getSession().getAttribute(FableConstant.USER_SESSION_KEY);
//        if (adminDO == null) {
//            result.setErrMsg("请重新登录!");
//            return result;
//        }
        if (id != null) {
            AdminUserDO adminUserDO = adminUserService.findDOUserById(id);
            if (adminUserDO == null) {
                result.setErrMsg("对象不存在!");
                return result;
            } else {
                adminUserDO.setStatus(0);
                adminUserService.update(adminUserDO);
            }
        }
        return result;
    }

    @RequestMapping("/saveAdminUser.json")
    @ResponseBody
    public JsonResult saveAdminUser(HttpServletRequest request, @ModelAttribute CreateAdminUserModel createAdminUserModel) {
        JsonResult jsonResult = new JsonResult();
//        AdminUserDO adminDO = (AdminUserDO) request.getSession().getAttribute(FableConstant.USER_SESSION_KEY);
//        if (adminDO == null) {
//            jsonResult.setCustomErrCode("-1", "未登录");
//            return jsonResult;
//        }
        try {
            if (checkExist(createAdminUserModel)) {
                jsonResult.setErrMsg("已存在用户!");
                return jsonResult;
            }
            if (createAdminUserModel.getId() != null) {
                AdminUserDO adminUserDO = adminUserService.findDOUserById(createAdminUserModel.getId());
                if (adminUserDO == null) {
                    logger.error("非法操作,param:{}", JSON.toJSONString(createAdminUserModel));
                    jsonResult.setErrMsg("非法操作!");
                    return jsonResult;
                }

                BeanUtils.copyProperties(createAdminUserModel, adminUserDO);
                adminUserService.update(adminUserDO);
            } else {
                AdminUserDO adminUserDO = new AdminUserDO();
                //初始化密码
                BeanUtils.copyProperties(createAdminUserModel, adminUserDO);
                adminUserService.add(adminUserDO);
            }
        } catch (Exception e) {
            logger.error("保存用户异常,param:{}", JSON.toJSONString(createAdminUserModel), e);
            jsonResult.setErrMsg("保存异常请联系管理员!");
            return jsonResult;
        }
        return jsonResult;
    }


    @RequestMapping("/editAdminUserPwd.json")
    @ResponseBody
    public JsonResult editAdminUserPwd(HttpServletRequest request, @ModelAttribute CreateAdminUserModel createAdminUserModel) {
        JsonResult jsonResult = new JsonResult();
        try {

            if (createAdminUserModel.getId() != null) {
                AdminUserDO adminUserDO = adminUserService.findDOUserById(createAdminUserModel.getId());
                if (adminUserDO == null) {
                    logger.error("非法操作,param:{}", JSON.toJSONString(createAdminUserModel));
                    jsonResult.setErrMsg("非法操作!");
                    return jsonResult;
                }
                adminUserDO.setPassword(createAdminUserModel.getPassword());
                adminUserService.update(adminUserDO);
            }
        } catch (Exception e) {
            logger.error("修改密码异常,param:{}", JSON.toJSONString(createAdminUserModel), e);
            jsonResult.setErrMsg("修改密码异常,请联系管理员!");
            return jsonResult;
        }
        return jsonResult;
    }

    private boolean checkExist(@ModelAttribute CreateAdminUserModel createAdminUserModel) {
        AdminUserQuery query = new AdminUserQuery();
        query.createCriteria().andStatusGreaterThanOrEqualTo(0).andLoginEqualTo(createAdminUserModel.getLogin());
        List<AdminUserDO> list = adminUserExtMapper.selectByQuery(query);
        if (!CollectionUtils.isEmpty(list)) {
            logger.warn("已存在用户,param:{}", JSON.toJSONString(createAdminUserModel));
            return true;
        }
        return false;
    }

}
